#!/usr/bin/env python
# -*- coding: utf-8 -*-
###################################################################
# Author: Wang donghao
# Date  : 2020.12
# wechat : 18250844478
###################################################################
import os
import pprint
from dayu_widgets.qt import *
from dayu_widgets import dayu_theme
from dayu_widgets.toast import MToast
from dayu_widgets.label import MLabel


class ErrorBox(QMessageBox):
    def __init__(self, parent=None, text=u''):
        super(ErrorBox, self).__init__(parent)
        dayu_theme.apply(self)
        self.main_layout = QHBoxLayout()
        self.main_label = MLabel(text).danger()
        self.main_layout.addWidget(self.main_label)
        self.setLayout(self.main_layout)
        self.setWindowFlags(Qt.WindowStaysOnTopHint)
        screen = QDesktopWidget().screenGeometry()
        size = self.geometry()
        self.move((screen.width() - size.width()) / 2, (screen.height() - size.height()) / 2)


# errorWindow = ErrorBox()


def permission_control(allowance=None, forbidden=None):
    def wrapper(func):
        def deal_permission(args):
            # pprint.pprint(args)
            # print get_permission(get_user()), allowance, forbidden
            user = os.environ.get('SG_PANDA')
            user_nick_name = os.environ.get('SG_PANDA_NICK_NAME')
            all_pandas_dict = args.get('selected')[0].get('sg_data').get('sg_panda')
            all_pandas = str(all_pandas_dict) + os.environ.get('WOK_CHECKER')
            # pprint.pprint(args)
            # print user, all_pandas, user_nick_name.decode('gbk').encode('utf-8')
            try:
                allow = 1
                if allowance:
                    if user not in all_pandas and user_nick_name.decode('gbk').encode('utf-8') not in all_pandas.encode('utf-8'):
                        allow = 0
                if forbidden:
                    if user in forbidden:
                        allow = 0
                if allow:
                    return func(args)
                else:
                    MToast.error(parent=args.get('widget'), text=u'您没有权限!')
                    return
            except Exception as e:
                MToast.error(parent=args.get('widget'), text=u'发生未知错误!\n%s'%e)
                print e
                return
        return deal_permission
    return wrapper

